import time


class DeviceBasic:
    def __init__(self, device, packages_name: str):
        self._device = device
        self._packages_name: str = packages_name

    def wait_element(self, element, timeout=30):
        """
        等待某个元素出现
        :param element:
        :param timeout:
        :return:
        """
        while timeout > 0:
            if element.exists:
                return True
            timeout -= 0.5
            if timeout > 0.5:
                time.sleep(0.5)
        return False

    def restart(self):
        self.stop()
        time.sleep(1)
        self.open()
        return True

    def open(self):
        self._device.app_start(self._packages_name)
        time.sleep(2)
        return True

    def stop(self):
        self._device.app_stop(self._packages_name)
        time.sleep(2)
        return True

    def is_foreground(self):
        app_current = self._device.current_app()
        return app_current["package"] == self._packages_name
